package com.guaoran.interview.in2019.compare;

import java.util.Date;
import java.util.Objects;

/**
 * @Author gucheng
 * @Description 比较示例 ： 当实现 equals 方法的时候，也要覆盖 hashCode 方法，
 * 原因是：基于散列的集合一起工作时，可以正常运作，如：hashMap、HashSet 和HashTable ，他们会用到 hashCode 方法来比较 是否是同一个元素。
 * 如果不覆盖的话，可
 * 2019-09-11 14:03
 */
public class EqualsDemo implements Comparable<EqualsDemo>{
    private Integer id;
    private String name;
    private Date createTime;

    @Override
    public int hashCode() {
        return (id == null ? 0 : id.hashCode()) ^
                (name == null ? 0 : name.hashCode()) ^
                (createTime == null ? 0 :createTime.hashCode());
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(!(obj instanceof EqualsDemo)){
            return false;
        }
        EqualsDemo demo = (EqualsDemo) obj;
        return (Objects.equals(id, demo.id))
                && (Objects.equals(name, demo.name))
                && (Objects.equals(createTime, demo.createTime));
    }

    @Override
    public String toString() {
        return "Demo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", createTime=" + createTime +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public int compareTo(EqualsDemo o) {

        return id.compareTo(o.id) + name.compareTo(o.name) + createTime.compareTo(o.createTime);
    }
}
